<?php
if(!defined('IN')) exit('Access Denied');
/*
	function list

	void sql_db( string dbhost, string dbuser, string dbpw, string dbname [, int pconnect] )
	bool sql_close()

	resource query( string sql )
	array fetch( resource query [, int method] )
	array fetch_one( string sql [, int method] )
	array fetch_all( string sql [, int method] )

	int num_rows( resource query )
	int affected_rows()
	int num_fields( resource query )

	int insert_id( [string table] )

	string error()
	int errno()

	bool free_result( resource query )

	array status( string table )

	void halt( [string sql] )

	string ver()
*/
class sql_db{
	var $querynum = 0;
	var $logit = 0;//日志记录
	var $debug = 1;//调试模式

	function sql_db($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0){
		global $forcego;
		if($pconnect) {
			if(!@mysql_pconnect($dbhost, $dbuser, $dbpw) && empty($forcego)) $this->halt();
		}else {
			if(!@mysql_connect($dbhost, $dbuser, $dbpw) && empty($forcego)) $this->halt();
		}
		@mysql_select_db($dbname);

		$ver = $this->ver();
		if($ver > '4.1') {
			$this->query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary");
			if($ver > '5.0.1') {
				$this->query("SET sql_mode=''");
			}
		}
		unset($ver);
	}
	function sql_close(){
		return mysql_close();
	}

	function query($sql){
		$query = @mysql_query($sql);
		if(!$query) {
			!empty($this->logit) && function_exists('AddLog') && AddLog($this->error(), 'sql', $sql);
			!empty($this->debug) && $this->halt($sql);
			return false;
		}
		$this->querynum++;
		return $query;
	}
	function fetch($query, $method = MYSQL_ASSOC){
		return mysql_fetch_array($query, $method);
	}
	function fetch_one($sql, $method = MYSQL_ASSOC){
		$query = $this->query($sql);
		if(false === $query) return false;
		return $this->fetch($query, $method);
	}
	function fetch_all($sql, $method = MYSQL_ASSOC){
		$query = $this->query($sql);
		if(false === $query) return false;
		$all = array();
		while($one = $this->fetch($query, $method)) {
			$all[] = $one;
		}
		return $all;
	}

	function num_rows($query){
		return mysql_num_rows($query);
	}
	function affected_rows(){
		return mysql_affected_rows();
	}
	function num_fields($query){
		return mysql_num_fields($query);
	}

	function insert_id($table = ''){
		if(!$table) return mysql_insert_id();
		$status = $this->status($table);
		return $status['Auto_increment'];
	}

	function error(){
		return $this->errno().': '.mysql_error();
	}
	function errno(){
		return mysql_errno();
	}

	function free_result($query){
		return mysql_free_result($query);
	}

	function status($table){
		return $this->fetch_one("SHOW TABLE STATUS LIKE '$table'");
	}

	function halt($sql = ''){
		function_exists('back') && back($this->error()."<br />$sql", 1);
		exit($this->error()."<br />$sql");
	}

	function ver(){
		return mysql_get_server_info();
	}
}
?>